package com.github.prontera.ueditor.util.upload;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * 本地文件存储
 */
@Component
public class FileRepository  {
	
	/**
	 * 上传文件存储的绝对路径
	 */
	@Value("${upload.absolute.file.path}")
	private String uploadFilePath;

	public String storeByExt(String path, String ext, MultipartFile file) throws IOException {
		String filename = UploadUtils.generateFilename(path, ext);
		File dest = new File(uploadFilePath,filename);
		dest = UploadUtils.getUniqueFile(dest);
		store(file, dest);
		return filename;
	}

	public String storeByFilename(String filename, MultipartFile file) throws IOException {
		File dest = new File(uploadFilePath,filename);
		store(file, dest);
		return filename;
	}

	public String storeByExt(String path, String ext, File file) throws IOException {
		String filename = UploadUtils.generateFilename(path, ext);
		File dest = new File(uploadFilePath,filename);
		dest = UploadUtils.getUniqueFile(dest);
		store(file, dest);
		return filename;
	}

	public String storeByFilename(String filename, File file) throws IOException {
		File dest = new File(uploadFilePath,filename);
		store(file, dest);
		return filename;
	}

	private void store(MultipartFile file, File dest) throws IOException {
		try {
			UploadUtils.checkDirAndCreate(dest.getParentFile());
			dest.setWritable(true);
			dest.setReadable(true);
			FileUtils.writeByteArrayToFile(dest, file.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}
	}

	private void store(File file, File dest) throws IOException {
		try {
			UploadUtils.checkDirAndCreate(dest.getParentFile());
			dest.setWritable(true);
			dest.setReadable(true);
			FileUtils.copyFile(file, dest);
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}
	}
	

}
